<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧处方新增界面 -->
      <el-col :span="14">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>新增处方</span>
            </div>
          </template>
          <el-form ref="prescriptionRef" :model="form" :rules="rules" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="患者id" prop="patientsId">
                  <el-select v-model="form.patientsId" placeholder="请选择患者" filterable clearable style="width: 100%"
                    @change="handlePatientChange">
                    <el-option v-for="item in patientOptions" :key="item.id" :label="item.name" :value="item.id">
                      <div class="patient-option">
                        <span class="patient-name">{{ item.name }}</span>
                        <span class="patient-id">ID: {{ item.id }}</span>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="医护人员id" prop="employeeId">
                  <el-input v-model="form.employeeId" placeholder="请输入医护人员id" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <el-divider content-position="center">处方明细信息</el-divider>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" icon="Plus" @click="handleAddPrescriptionDetail">添加</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" icon="Delete" @click="handleDeletePrescriptionDetail">删除</el-button>
              </el-col>
            </el-row>

            <el-table :data="prescriptionDetailList" :row-class-name="rowPrescriptionDetailIndex"
              @selection-change="handlePrescriptionDetailSelectionChange" ref="prescriptionDetail">
              <el-table-column type="selection" width="45" align="center" />
              <el-table-column label="序号" align="center" prop="index" width="50" />
              <el-table-column label="药品选择" prop="medicationId" width="150">
                <template #default="scope">
                  <el-row :gutter="10">
                    <el-col :span="24">
                      <el-select v-model="scope.row.medicationId" placeholder="选择药品" filterable clearable
                        @change="(value) => handleMedicationChange(value, scope.$index)" style="width: 100%">
                        <el-option v-for="item in getFilteredMedications(scope.$index)" :key="item.id"
                          :label="item.name" :value="item.id">
                          <div class="medication-option">
                            <div class="medication-info">
                              <span class="medication-name">{{ item.name }}</span>
                              <div class="medication-meta">
                                <span class="medication-code">编码：{{ item.code }}</span>
                                <span class="medication-type">剂型：{{ item.dosageFormText }}</span>
                                <span class="medication-category">类别：{{ item.categoryText }}</span>
                              </div>
                            </div>
                            <div class="medication-details">
                              <span class="stock" :class="{ 'low-stock': item.stock < 10 }">库存: {{ item.stock }}</span>
                              <span class="price">￥{{ item.price }}</span>
                            </div>
                          </div>
                        </el-option>
                      </el-select>
                    </el-col>
                  </el-row>
                </template>
              </el-table-column>
              <el-table-column label="用药剂量" prop="dosage" width="120">
                <template #default="scope">
                  <span>{{ scope.row.dosage }}</span>
                </template>
              </el-table-column>
              <el-table-column label="药品总量" prop="quantity" width="160">
                <template #default="scope">
                  <el-input-number v-model="scope.row.quantity" placeholder="请输入药品总量" :min="1"
                    :max="scope.row.stockQuantity || 999999" @change="(value) => calculateTotal(scope.$index)"
                    style="width: 100px" />
                  <div class="stock-info" v-if="scope.row.stockQuantity">
                    <span :class="{ 'stock-warning': scope.row.stockQuantity < 10 }">库存: {{ scope.row.stockQuantity
                    }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="单价" prop="price" width="90">
                <template #default="scope">
                  <span>￥{{ scope.row.price }}</span>
                </template>
              </el-table-column>
              <el-table-column label="总价" prop="totalAmount" width="90">
                <template #default="scope">
                  <span>￥{{ scope.row.totalAmount }}</span>
                </template>
              </el-table-column>
            </el-table>

            <el-form-item label="实收金额" prop="money" style="margin-top: 20px;">
              <el-input v-model="form.money" placeholder="请输入实收金额" readonly />
            </el-form-item>

            <el-form-item style="margin-top: 20px;">
              <el-button type="primary" @click="submitForm">提交处方</el-button>
              <el-button @click="reset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧患者和处方信息 -->
      <el-col :span="10">
        <!-- 患者信息卡片 -->
        <el-card class="box-card-c" style="margin-bottom: 20px;">
          <template #header>
            <div class="card-header">
              <span>患者信息</span>
              <div>
                <el-button type="primary" link @click="handleViewPatient">查看详情</el-button>
                <el-button type="primary" link @click="handleToPatients">跳转到患者管理</el-button>
              </div>
            </div>
          </template>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="患者ID">{{ patientInfo.id }}</el-descriptions-item>
            <el-descriptions-item label="姓名">{{ patientInfo.name }}</el-descriptions-item>
            <el-descriptions-item label="性别">
              <dict-tag :options="sys_user_sex" :value="patientInfo.gender" />
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ patientInfo.phone }}</el-descriptions-item>
            <el-descriptions-item label="出生日期">{{ patientInfo.birthDate }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 处方历史记录卡片 -->
        <el-card class="box-card-c">
          <template #header>
            <div class="card-header">
              <span>处方历史记录</span>
              <div>
                <!-- <el-button type="primary" link @click="handleViewPrescription">查看详情</el-button> -->
                <el-button type="primary" link @click="handleToPrescription">跳转到处方管理</el-button>
              </div>
            </div>
          </template>
          <el-table :data="prescriptionList" style="width: 100%" @row-click="handleView">
            <el-table-column prop="createTime" label="开据时间" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <dict-tag :options="sys_prescription_status" :value="scope.row.status" />
              </template>
            </el-table-column>
            <el-table-column prop="money" label="金额" width="100">
              <template #default="scope">
                <span>￥{{ scope.row.money }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 查看患者详细对话框 -->
    <el-dialog title="患者详细信息" v-model="patientViewOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="患者ID">{{ patientInfo.id }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ patientInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">
          <dict-tag :options="sys_user_sex" :value="patientInfo.gender" />
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ patientInfo.phone }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ patientInfo.user }}</el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ patientInfo.birthDate }}</el-descriptions-item>
      </el-descriptions>
      <el-divider content-position="center">过敏信息</el-divider>
      <el-table :data="viewForm.conflictList">
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="药品名称" prop="medicationId" align="center">
          <template #default="scope">
            {{ getMedicationName(scope.row.medicationId) }}
          </template>
        </el-table-column>
        <el-table-column label="基本症状" prop="symptom" align="center" />
      </el-table>
    </el-dialog>

    <!-- 查看处方详细对话框 -->
    <el-dialog title="处方详细信息" v-model="viewOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="处方ID">{{ viewForm.id }}</el-descriptions-item>
        <el-descriptions-item label="患者ID">{{ viewForm.patientsId }}</el-descriptions-item>
        <el-descriptions-item label="医护人员ID">{{ viewForm.employeeId }}</el-descriptions-item>
        <el-descriptions-item label="处方开据时间">{{ parseTime(viewForm.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <dict-tag :options="sys_prescription_status" :value="viewForm.status" />
        </el-descriptions-item>
        <el-descriptions-item label="实收金额">{{ viewForm.money }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="center">处方明细信息</el-divider>
      <el-table :data="viewForm.prescriptionDetailList">
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="药品名称" prop="medicationName" align="center" />
        <el-table-column label="用药剂量" prop="dosage" align="center" />
        <el-table-column label="药品总量" prop="quantity" align="center" />
        <el-table-column label="单价" prop="price" align="center" />
        <el-table-column label="总价" prop="totalAmount" align="center" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="PrescriptionWork">
import {
  listPrescription,
  getPrescription,
  addPrescription,
  getUnreadReminders,
} from "@/api/prescription/prescription";
import { listMedication } from "@/api/medication/medication";
import { getPatients, listPatients } from "@/api/patients/patients";
import { getEmployeeByUsername } from "@/api/employee/employee";
import { getInfo } from "@/api/login";
import useUserStore from "@/store/modules/user";
import { listNotice } from "@/api/system/notice";

const { proxy } = getCurrentInstance();
const { sys_prescription_status, sys_user_sex } = proxy.useDict("sys_prescription_status", "sys_user_sex");
const userStore = useUserStore();

const prescriptionList = ref([]);
const prescriptionDetailList = ref([]);
const viewOpen = ref(false);
const patientViewOpen = ref(false);
const viewForm = ref({});
const patientInfo = ref({});
const medicationOptions = ref([]);
const categoryOptions = ref([]);
const dosageFormOptions = ref([]);
const checkedPrescriptionDetail = ref([]);
const patientOptions = ref([]);

const data = reactive({
  form: {
    patientsId: null,
    employeeId: null,
    money: 0
  },
  rules: {
    patientsId: [
      { required: true, message: "患者id不能为空", trigger: "blur" },
    ],
    employeeId: [
      { required: true, message: "医护人员id不能为空", trigger: "blur" },
    ],
  },
});

const { form, rules } = toRefs(data);

// 获取患者信息
function getPatientInfo(patientId) {
  getPatients(patientId).then(response => {
    patientInfo.value = response.data;
    viewForm.value = response.data;
  });
}

// 获取患者列表
function getPatientList() {
  listPatients({
    pageNum: 1,
    pageSize: 100
  }).then(response => {
    patientOptions.value = response.rows;
  });
}

// 处理患者选择变化
function handlePatientChange(value) {
  if (value) {
    getPatientInfo(value);
    getPrescriptionList(value);
  } else {
    patientInfo.value = {};
    prescriptionList.value = [];
  }
}

// 获取处方列表
function getPrescriptionList(patientId) {
  listPrescription({ patientsId: patientId }).then(response => {
    prescriptionList.value = response.rows;
  });
}

// 获取药品列表
function getMedicationList() {
  listMedication({
    pageNum: 1,
    pageSize: 100,
    status: '0'
  }).then(response => {
    medicationOptions.value = response.rows;
    // 提取所有不重复的类别和剂型，并转换为中文显示
    const categories = new Set();
    const dosageForms = new Set();

    // 药品类别字典
    const categoryMap = {
      0: '其他',
      1: '抗生素类',
      2: '抗病毒药物',
      3: '抗真菌药物',
      4: '抗肿瘤药物',
      5: '镇痛药物',
      6: '抗抑郁药物'
    };

    // 剂型字典
    const dosageFormMap = {
      0: '其他',
      1: '口服',
      2: '注射',
      3: '外用',
      4: '吸入'
    };

    medicationOptions.value.forEach(item => {
      // 转换类别显示
      const categoryText = categoryMap[item.type] || '其他';
      categories.add(categoryText);
      item.categoryText = categoryText;

      // 转换剂型显示
      const dosageFormText = dosageFormMap[item.dosageForm] || '其他';
      dosageForms.add(dosageFormText);
      item.dosageFormText = dosageFormText;
    });

    categoryOptions.value = Array.from(categories);
    dosageFormOptions.value = Array.from(dosageForms);
  });
}

// 根据ID获取药品名称
function getMedicationName(id) {
  const medication = medicationOptions.value.find(item => item.id === id);
  return medication ? medication.name : id;
}

// 获取当前登录用户的医护人员信息
async function getCurrentEmployee() {
  try {
    const response = await getInfo();
    const username = response.user.userName;
    console.log("Current user:", response.user);

    if (!username) {
      proxy.$modal.msgError("未获取到当前登录用户信息");
      return;
    }

    const employeeResponse = await getEmployeeByUsername(username);
    if (employeeResponse.data) {
      form.value.employeeId = employeeResponse.data.id;
    } else {
      proxy.$modal.msgError("未找到对应的医护人员信息");
    }
  } catch (error) {
    console.error("Error getting employee info:", error);
    proxy.$modal.msgError("获取医护人员信息失败：" + error);
  }
}

// 跳转到患者管理页面
function handleToPatients() {
  proxy.$router.push({
    path: '/patients/patients',
    name: 'Patients',
    meta: {
      title: '患者管理',
      icon: 'patients'
    }
  }).catch(err => {
    console.error('Navigation error:', err);
    proxy.$modal.msgError('跳转失败：' + err.message);
  });
}

// 跳转到处方管理页面
function handleToPrescription() {
  console.log('Attempting to navigate to prescription management...');
  proxy.$router.push({
    path: '/prescription/prescription',
    name: 'Prescription',
    meta: {
      title: '处方管理',
      icon: 'prescription'
    }
  }).catch(err => {
    console.error('Navigation error:', err);
    proxy.$modal.msgError('跳转失败：' + err.message);
  });
}

/** 处方明细序号 */
function rowPrescriptionDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 处方明细添加按钮操作 */
function handleAddPrescriptionDetail() {
  let obj = {
    medicationId: undefined,
    medicationName: '',
    dosage: '',
    quantity: 1,
    price: 0,
    totalAmount: 0,
    categoryFilter: '',
    dosageFormFilter: '',
    stockQuantity: 0
  };
  prescriptionDetailList.value.push(obj);
}

/** 处方明细删除按钮操作 */
function handleDeletePrescriptionDetail() {
  if (checkedPrescriptionDetail.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的处方明细数据");
  } else {
    proxy.$modal.confirm('是否确认删除选中的数据项？').then(() => {
      const prescriptionDetails = prescriptionDetailList.value;
      const checkedPrescriptionDetails = checkedPrescriptionDetail.value;
      prescriptionDetailList.value = prescriptionDetails.filter(function (item) {
        return checkedPrescriptionDetails.indexOf(item.index) == -1;
      });
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
  }
}

/** 复选框选中数据 */
function handlePrescriptionDetailSelectionChange(selection) {
  checkedPrescriptionDetail.value = selection.map((item) => item.index);
}

/** 查看患者详情 */
function handleViewPatient() {
  if (!patientInfo.value.id) {
    proxy.$modal.msgError("请先选择患者");
    return;
  }
  patientViewOpen.value = true;
}

/** 查看处方详情 */
function handleViewPrescription() {
  if (!prescriptionList.value || prescriptionList.value.length === 0) {
    proxy.$modal.msgError("暂无处方记录");
    return;
  }
  // 默认查看最新的处方
  const latestPrescription = prescriptionList.value[0];
  getPrescription(latestPrescription.id).then((response) => {
    viewForm.value = response.data;
    viewOpen.value = true;
  });
}

/** 查看按钮操作 */
function handleView(row) {
  getPrescription(row.id).then((response) => {
    viewForm.value = response.data;
    viewOpen.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["prescriptionRef"].validate((valid) => {
    if (valid) {
      // 检查库存
      const stockError = prescriptionDetailList.value.find(detail =>
        detail.quantity > detail.stockQuantity
      );

      if (stockError) {
        proxy.$modal.msgError("药品数量不能超过库存数量！");
        return;
      }

      // 检查是否存在治疗中的处方
      listPrescription({ patientsId: form.value.patientsId, status: '2' }).then(response => {
        if (response.rows && response.rows.length > 0) {
          proxy.$modal.msgError("该患者已有治疗中的处方，不能新增处方！");
          return;
        }

        // 如果没有治疗中的处方，继续提交
        form.value.prescriptionDetailList = prescriptionDetailList.value;
        addPrescription(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          reset();
        });
      });
    }
  });
}

/** 重置按钮操作 */
function reset() {
  form.value = {
    patientsId: null,
    employeeId: null,
    money: 0
  };
  prescriptionDetailList.value = [];
  proxy.resetForm("prescriptionRef");
  // 重新获取医护人员ID
  getCurrentEmployee();
}

// 初始化
onMounted(() => {
  getMedicationList();
  getCurrentEmployee();
  getPatientList();
});

/** 处理药品类别变化 */
function handleCategoryChange(value, index) {
  const row = prescriptionDetailList.value[index];
  row.medicationId = undefined; // 清空已选药品
  row.dosageFormFilter = ''; // 清空剂型筛选
}

/** 处理剂型变化 */
function handleDosageFormChange(value, index) {
  const row = prescriptionDetailList.value[index];
  row.medicationId = undefined; // 清空已选药品
}

/** 处理药品选择变化 */
function handleMedicationChange(value, index) {
  const row = prescriptionDetailList.value[index];
  const medication = medicationOptions.value.find(item => item.id === value);
  if (medication) {
    row.medicationName = medication.name;
    row.price = medication.price;
    row.stockQuantity = medication.stock;
    row.dosage = medication.dosage;
    calculateTotal(index);
  }
}

/** 计算总价 */
function calculateTotal(index) {
  const row = prescriptionDetailList.value[index];
  row.totalAmount = row.price * row.quantity;
  // 计算所有明细的总价
  form.value.money = prescriptionDetailList.value.reduce((sum, item) => sum + (item.totalAmount || 0), 0);
}

/** 获取过滤后的药品列表 */
function getFilteredMedications(index) {
  const row = prescriptionDetailList.value[index];
  return medicationOptions.value.filter(item => {
    const matchCategory = !row.categoryFilter || item.categoryText === row.categoryFilter;
    const matchDosageForm = !row.dosageFormFilter || item.dosageFormText === row.dosageFormFilter;
    return matchCategory && matchDosageForm;
  });
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
}

.box-card {
  margin-bottom: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 580px;

  :deep(.el-card__body) {
    flex: 1;
    overflow: auto;
    padding: 20px;
  }
}

.box-card-c {
  margin-bottom: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 280px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-form) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-table) {
  height: 250px;
  overflow: auto;
}

:deep(.el-table__body-wrapper) {
  overflow-x: hidden;
}

.medication-option {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 8px 0;

  .medication-info {
    flex: 1;
    margin-right: 15px;

    .medication-name {
      font-weight: bold;
      margin-bottom: 8px;
      display: block;
      font-size: 14px;
    }

    .medication-meta {
      font-size: 12px;
      color: #666;
      display: flex;
      flex-wrap: wrap;
      gap: 10px;

      span {
        white-space: nowrap;
        background-color: #f5f7fa;
        padding: 2px 6px;
        border-radius: 4px;
      }
    }
  }

  .medication-details {
    text-align: right;
    min-width: 120px;

    .stock {
      display: block;
      font-size: 12px;
      color: #67C23A;
      margin-bottom: 6px;
      padding: 2px 6px;
      border-radius: 4px;
      background-color: #f0f9eb;

      &.low-stock {
        color: #F56C6C;
        background-color: #fef0f0;
      }
    }

    .price {
      font-weight: bold;
      color: #F56C6C;
      font-size: 14px;
      display: block;
      padding: 2px 6px;
      border-radius: 4px;
      background-color: #fef0f0;
    }
  }
}

.stock-info {
  margin-top: 8px;
  font-size: 12px;
  text-align: center;

  .stock-warning {
    color: #F56C6C;
    background-color: #fef0f0;
    padding: 2px 6px;
    border-radius: 4px;
  }
}

:deep(.el-table) {
  .el-table__header-wrapper {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: bold;
      padding: 12px 0;
    }
  }

  .el-table__row {
    td {
      padding: 12px 0;
    }
  }
}

:deep(.el-input-number) {
  .el-input__wrapper {
    padding: 0 8px;
  }
}

:deep(.el-select) {
  width: 100%;

  .el-input__wrapper {
    padding: 0 8px;
  }
}

:deep(.el-table__body) {
  .el-table__row {
    &:hover {
      td {
        background-color: #f5f7fa;
      }
    }
  }
}

.patient-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;

  .patient-name {
    font-weight: bold;
  }

  .patient-id {
    color: #909399;
    font-size: 12px;
  }
}
</style>
